import React, { Component } from 'react'
import { history } from 'umi'
import {
  Row,
  Col,
  Divider,
  Input,
  Select,
  Button,
  DatePicker,
  Icon,
  message,
  Spin,
  Upload,
} from 'antd'

import {
  getadminDataByToken,
  getTagInfo,
  updateArticle,
  getArticleById,
  uploadImage,
} from '@/services/admin'
import './index.less'
import moment from 'moment'

// 导入markdown组件
import MarkdownIt from 'markdown-it'
import MdEditor from 'react-markdown-editor-lite'
import hljs from 'highlight.js'
import 'react-markdown-editor-lite/lib/index.css'
import 'highlight.js/styles/atom-one-light.css'

import { serverBaseUrl } from '@/assets/js/ConstVariable'
import debounce from '@/assets/js/debounce'
const mdParser = MarkdownIt({
  html: true,
  linkify: true,
  typographer: true,
  highlight(str, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return hljs.highlight(lang, str).value
      } catch (__) {}
    }
    return '' // 使用额外的默认转义
  },
})

const { Option } = Select
const { TextArea } = Input
export default class AddArticle extends Component {
  state = {
    articleId: 0, //是0就是新添加否则是修改
    articleTitle: '',
    articleContent: '',
    articleMd: '',
    introducemd: '', //简介markdown内容
    introducehtml: '', //简介的html内容
    updateDate: '', //更新日期
    tagList: [], //文章类别
    selectedType: '', //选择的文章类别
    isLoading: true,
    imageUrl: '', // 图片地址
    isImageLoad: false, //图片加载中
  }

  componentDidMount() {
    this.getTagInfo()
    this.initArticleInfo()

    document.title = '添加文章'
    this.quickSave()
  }

  componentWillUnmount() {
    document.removeEventListener('keydown', this.save)
  }
  // 快捷保存
  quickSave = () => {
    const newHandleArticle = debounce(this.handleArticle, 300)
    this.save = document.addEventListener('keydown', (e) => {
      if (e.keyCode == 83 && (navigator.platform.match('Mac') ? e.metaKey : e.ctrlKey)) {
        e.preventDefault()
        newHandleArticle()
      }
    })
  }

  // 获取用户信息
  getadminDataByToken = async () => {
    const res = await getadminDataByToken()
  }

  // 初始化文章信息
  initArticleInfo = async () => {
    const id = history?.location?.query?.id || sessionStorage.getItem('id')
    if (!!id && id != 0) {
      const res = await getArticleById(id)
      if (res?.status === 200) {
        console.log(res.data)
        const articleInfo = res.data[0]
        await this.setState({
          articleId: articleInfo.id,
          articleTitle: articleInfo.title,
          // articleContent: turndownService.turndown(articleInfo.content),
          articleContent: articleInfo.content,
          introducemd: mdParser.render(articleInfo.introduce), //简介markdown内容
          introducehtml: articleInfo.introduce, //简介的html内容
          selectedType: articleInfo.tagId,
          imageUrl: articleInfo.url,
        })
      }
    }
    setTimeout(() => {
      this.setState({ isLoading: false })
    }, 200)
  }
  // 文章内容发生改变
  handleEditorChange = () => {
    this.setState({ articleContent: this.MdEditorRef.state.text })
  }

  // 文章简介改变
  changeIntroduce = (e) => {
    let introducemd = mdParser.render(e.target.value)
    this.setState({ introducehtml: e.target.value, introducemd })
  }

  // 获取标签
  getTagInfo = async () => {
    const res = await getTagInfo()
    if (res?.status === 200) {
      this.setState({ tagList: res.tagList })
    }
  }

  // 上传图片
  handleImageUpload(file, callback) {
    return new Promise(() => {
      const reader = new FileReader()
      reader.onload = async () => {
        const res = await uploadImage(reader.result)
        callback(serverBaseUrl + res.path)
      }
      reader.readAsDataURL(file)
    })
  }

  // 处理文章
  handleArticle = async (operator = 0) => {
    let {
      articleId,
      articleStatus,
      selectedType,
      articleTitle,
      articleContent,
      introducehtml,
      imageUrl,
    } = this.state
    // 验证信息
    if (!selectedType) {
      message.error('必须选择文章类别')
      return false
    } else if (!articleTitle) {
      message.error('文章名称不能为空')
      return false
    } else if (!articleContent) {
      message.error('文章内容不能为空')
      return false
    } else if (!introducehtml) {
      message.error('简介不能为空')
      return false
    }
    //暂存
    if (operator === 0) {
      const res = await updateArticle({
        articleTitle,
        articleContent,
        introducehtml,
        selectedType,
        articleStatus: 0,
        articleId,
        imageUrl,
      })
      if (res?.status === 200) {
        message.destroy()
        message.success('保存成功')
        const id = res.data.insertId || articleId
        this.setState({ articleId: id })
        sessionStorage.setItem('id', id)
      }
      // 发布
    } else {
      const res = await updateArticle({
        articleTitle,
        articleContent,
        introducehtml,
        selectedType,
        articleStatus: 1,
        articleId,
        imageUrl,
      })

      if (res?.status === 200) {
        this.setState({ articleId: res.data.insertId })
        sessionStorage.setItem('id', res.data.insertId)
        message.destroy()
        message.success('发布成功')
      }
    }
  }

  // 新建文章
  resetArticle = async () => {
    await this.setState({
      articleId: 0,
      articleTitle: '',
      articleContent: '',
      introducemd: '',
      introducehtml: '',
      selectedType: '', //选择的文章类别
      isLoading: true,
      imageUrl: '',
    })

    this.setState({ isLoading: false })
    sessionStorage.removeItem('id')
  }

  // 图片转base64 方法1
  getBase64 = (img, callback) => {
    const reader = new FileReader()
    reader.addEventListener('load', () => callback(reader.result))
    reader.readAsDataURL(img)
  }

  // 上传图片需要的验证
  beforeUpload = (file) => {
    const isLt5M = file.size / 1024 / 1024 < 5
    if (!isLt5M) {
      message.error('图片大小不能超过5M!')
    }
    return isLt5M
  }
  // 处理上传图片点击
  handleChange = async (info) => {
    info.file.status = 'done'
    if (info.file.status === 'uploading') {
      this.setState({ isImageloading: true })
      return
    }
    if (info.file.status === 'done') {
      this.getBase64(info.file.originFileObj, (imageUrl) =>
        this.setState({
          imageUrl,
          isImageloading: false,
        }),
      )
    }
  }
  render() {
    const { articleContent, introducehtml, tagList, introducemd, isLoading, imageUrl } = this.state
    const handleImageUrl = imageUrl?.indexOf('base64') === -1 ? serverBaseUrl + imageUrl : imageUrl

    return (
      <div>
        {isLoading ? (
          <Spin tip="Loading..." />
        ) : (
          <Row gutter={10} className="add-article">
            {/* 左侧 */}
            <Col span={18}>
              {/* 标题选择 */}
              <Row gutter={10}>
                <Col span={18}>
                  <Input
                    placeholder="博客标题"
                    onChange={(e) => {
                      this.setState({ articleTitle: e.target.value })
                    }}
                    value={this.state.articleTitle}
                  />
                </Col>
                {/* 标签选择 */}
                <Col span={6}>
                  &nbsp;
                  <Select
                    style={{ width: 150 }}
                    placeholder="请选择标签"
                    onChange={(value) => this.setState({ selectedType: value })}
                    value={this.state.selectedType}
                  >
                    {tagList.map((item) => {
                      return (
                        <Option value={item.id} key={item.id}>
                          <Icon type={item.icon} />
                          &nbsp;
                          {item.tag_name}
                        </Option>
                      )
                    })}
                  </Select>
                </Col>
              </Row>
              <br />
              <Row>
                <MdEditor
                  style={{ height: '450px' }}
                  renderHTML={(text) => mdParser.render(text)}
                  onChange={this.handleEditorChange}
                  onImageUpload={this.handleImageUpload}
                  placeholder="请输入文章内容"
                  defaultValue={articleContent}
                  ref={(e) => (this.MdEditorRef = e)}
                />
              </Row>
            </Col>
            {/* 右侧 */}
            <Col span={6}>
              <Row>
                {/* 发布、暂存区域 */}
                <Col span={24} style={{ marginBottom: 10 }}>
                  <Button onClick={() => this.handleArticle(0)}>暂存</Button>
                  <Button
                    type="primary"
                    style={{ margin: '0 10px' }}
                    onClick={() => this.handleArticle(1)}
                  >
                    发布
                  </Button>
                  <Button type="primary" onClick={this.resetArticle}>
                    新建
                  </Button>
                  <br />
                </Col>
                {/* 简介区域 */}
                <Col span={24}>
                  <TextArea
                    rows={5}
                    autoSize={false}
                    placeholder="请填写简介..."
                    onChange={this.changeIntroduce}
                    value={this.state.introducehtml}
                    style={{ marginTop: 10 }}
                  />
                  <br />
                  <br />
                  <div
                    className="introduce-html"
                    dangerouslySetInnerHTML={{ __html: introducemd }}
                  />
                </Col>
                <Col span={24}>
                  <Divider style={{ padding: '10px 0', color: 'orange' }}>上传封面</Divider>
                  <Upload
                    listType="picture-card"
                    className="avatar-uploader"
                    showUploadList={false}
                    beforeUpload={this.beforeUpload}
                    customRequest={() => {}}
                    onChange={this.handleChange}
                  >
                    {this.state.imageUrl ? (
                      <div className="image-area">
                        <Icon
                          type="close"
                          style={{ color: 'orange' }}
                          onClick={(e) => {
                            e.stopPropagation()
                            this.setState({ imageUrl: '' })
                          }}
                        />
                        <img src={handleImageUrl} alt="avatar" style={{ width: '100%' }} />
                      </div>
                    ) : (
                      <div>
                        <Icon type={this.state.isImageLoad ? 'loading' : 'plus'} />
                        <div className="ant-upload-text">Upload</div>
                      </div>
                    )}
                  </Upload>
                </Col>
              </Row>
            </Col>
          </Row>
        )}
      </div>
    )
  }
}
